package ULHT.LIG2N1.RC.CLIENT;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.SocketException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class UDPMulticastThread extends Thread {

    private MulticastSocket socket;
    private InetAddress group;
    private boolean stopped = false;

    public UDPMulticastThread(MulticastSocket ds, String group) throws SocketException {
        this.socket = ds;
        try {
            this.group = InetAddress.getByName(group);
            //this.socket.joinGroup(this.group);
        } catch (Exception ex) {
            Logger.getLogger(UDPMulticastThread.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void halt() {
        this.stopped = true;
    }
//TODO porque é que o buffer parte a string? é na recepção ou no envio?

    @Override
    public void run() {
        byte[] buffer = new byte[65507];
        while (true) {
            if (stopped) {
                return;
            }
            DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
            try {
                this.socket.receive(dp);
                String s = new String(dp.getData());
                //janela.areaDeTexto.setText(s);
                System.out.println(s);
            } catch (IOException e) {
                System.err.println(e);
            }
        }
    }
}
